// admin/system/handler/user_handler.go
package handler

import (
	"go-admin1/admin/system/model"
	"go-admin1/admin/system/service"
	"go-admin1/internal/common/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

// UserHandler 用户控制器
type UserHandler struct {
	userService service.UserService
}

// NewUserHandler 创建用户控制器实例
func NewUserHandler() *UserHandler {
	return &UserHandler{
		userService: service.NewUserService(),
	}
}

// GetUser 获取用户详情
func (h *UserHandler) GetUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		utils.FailResponse[string](c, "参数错误")
		return
	}

	user, err := h.userService.GetUserByIDWithCache(id)
	if err != nil {
		utils.FailResponse[string](c, "用户不存在")
		return
	}
	utils.OkResponse(c, user)
}

// CreateUser 创建用户
func (h *UserHandler) CreateUser(c *gin.Context) {
	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		utils.FailResponse[string](c, "参数错误")
		return
	}

	if err := h.userService.CreateUser(&user); err != nil {
		utils.FailResponse[string](c, "创建用户失败")
		return
	}
	utils.OkResponseNoDataWithMessage[string](c, "创建成功")
}

// UpdateUser 更新用户
func (h *UserHandler) UpdateUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		utils.FailResponse[string](c, "参数错误")
		return
	}

	var user model.User
	if err := c.ShouldBindJSON(&user); err != nil {
		utils.FailResponse[string](c, "参数错误")
		return
	}
	user.ID = id

	if err := h.userService.UpdateUser(&user); err != nil {
		utils.FailResponse[string](c, "更新失败")
		return
	}
	utils.OkResponseNoDataWithMessage[string](c, "更新成功")
}

// DeleteUser 删除用户
func (h *UserHandler) DeleteUser(c *gin.Context) {
	idStr := c.Param("id")
	id, err := strconv.ParseUint(idStr, 10, 64)
	if err != nil {
		utils.FailResponse[string](c, "参数错误")
		return
	}

	if err := h.userService.DeleteUser(id); err != nil {
		utils.FailResponse[string](c, "删除失败")
		return
	}
	utils.OkResponseNoDataWithMessage[string](c, "删除成功")
}

// ListUsers 用户列表
func (h *UserHandler) ListUsers(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "10"))

	users, total, err := h.userService.ListUsers(page, pageSize)
	if err != nil {
		utils.FailResponse[string](c, "获取用户列表失败")
		return
	}

	resultData := map[string]interface{}{
		"list":  users,
		"total": total,
	}
	utils.OkResponse(c, resultData)
}
